//
//  ComparisonTableView.m
//  SecondPage
//
//  Created by winston on 13-4-16.
//  Copyright (c) 2013年 winston. All rights reserved.
//

#import "ComparisonTableView.h"
#import "ComparisonTableCell.h"
#import "ComparisonCarHeader.h"
#import "ComparisonModel.h"
#import "ComparisonTableHeader.h"
#import "ComparisonButton.h"
#import "ComparisonSelectView.h"
#import "../../ResourceLoader/ResourceLoader/ResourceLoader.h"

#define BARWIDTH        245
#define FirstWIDTH      225

@interface ComparisonTableView (PrivateMethods)

@end

@implementation ComparisonTableView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self setBackgroundColor:[UIColor whiteColor]];
        
        UILabel * signlabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 17, 30, 30)];
        signlabel.backgroundColor = [UIColor clearColor];
        signlabel.textColor = [UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:1];
        signlabel.textAlignment = NSTextAlignmentLeft;
        signlabel.font = [UIFont fontWithName:@"Arial" size:30];
        [signlabel setText:@"*"];
        [self addSubview:signlabel];
        [signlabel release];
        
        UILabel * datasourcelabel = [[UILabel alloc] initWithFrame:CGRectMake(28, 15, 60, 20)];
        datasourcelabel.backgroundColor = [UIColor clearColor];
        datasourcelabel.textColor = [UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:1];
        datasourcelabel.textAlignment = NSTextAlignmentLeft;
        datasourcelabel.font = [UIFont fontWithName:@"Arial" size:13];
        [datasourcelabel setText:@"数据来源:"];
        [self addSubview:datasourcelabel];
        [datasourcelabel release];
        
        UILabel * datasourcelabel1 = [[UILabel alloc] initWithFrame:CGRectMake(88, 15, 60, 20)];
        datasourcelabel1.backgroundColor = [UIColor clearColor];
        datasourcelabel1.textColor = [UIColor blackColor];
        datasourcelabel1.textAlignment = NSTextAlignmentLeft;
        datasourcelabel1.font = [UIFont fontWithName:@"Arial" size:13];
        [datasourcelabel1 setText:@"汽车之家"];
        [self addSubview:datasourcelabel1];
        [datasourcelabel1 release];
        
        UILabel * datasourcelabel2 = [[UILabel alloc] initWithFrame:CGRectMake(10, 35, 180, 12)];
        datasourcelabel2.backgroundColor = [UIColor clearColor];
        datasourcelabel2.textColor = [UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:1];
        datasourcelabel2.textAlignment = NSTextAlignmentLeft;
        datasourcelabel2.font = [UIFont fontWithName:@"Arial" size:10];
        [datasourcelabel2 setText:@"数据仅供参考，具体参数以各厂发布为准"];
        [self addSubview:datasourcelabel2];
        [datasourcelabel2 release];
        
        
        tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 50, BARWIDTH, frame.size.height-50) style:UITableViewStyleGrouped];
        [tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        [tableView setShowsHorizontalScrollIndicator:false];
        [tableView setShowsVerticalScrollIndicator:false];
        [tableView setDelegate:self];
        [tableView setDataSource:self];
        [self addSubview:tableView];
        [tableView release];
        [tableView setBackgroundView:[[[UIView alloc] init] autorelease]];
        
        addBtn = [[UIButton alloc]initWithFrame:CGRectMake(80+BARWIDTH, 50, 210, 165)];
        [addBtn.layer setBorderColor:[UIColor colorWithRed:0.8157 green:0.8157 blue:0.8157 alpha:1].CGColor];
        [addBtn.layer setBorderWidth:1.0];
        
        UIImageView * addView = [[UIImageView alloc]initWithFrame:CGRectMake(55, (addBtn.frame.size.height-22)/2, 22, 22)];
        [addView setImage:[UIImage imageNamed:@"AllAuto_Comparison_Button_Add"]];
        [addBtn addSubview:addView];
        [addView release];
        
        UILabel * nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(85, 0, addBtn.frame.size.width-90, addBtn.frame.size.height)];
        nameLabel.backgroundColor = [UIColor clearColor];
        nameLabel.textColor = [UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:1];
        nameLabel.textAlignment = NSTextAlignmentLeft;
        nameLabel.font = [UIFont fontWithName:@"Arial" size:18];
        [nameLabel setText:@"添加竞品"];
        [addBtn addSubview:nameLabel];
        [nameLabel release];
        
        [addBtn addTarget:self action:@selector(onAddCar:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:addBtn];
        [addBtn release];
        
        
        btnAll = [[ComparisonButton alloc]initWithFrame:CGRectMake(frame.size.width-80,300,80,40)];
        [btnAll addTarget:self action:@selector(onShowAll:) forControlEvents:UIControlEventTouchUpInside];
        [btnAll setTitle:@"全部参数"];
        [self addSubview:btnAll];
        [btnAll release];
        
        btnFilter = [[ComparisonButton alloc]initWithFrame:CGRectMake(frame.size.width-80,340,80,40)];
        [btnFilter addTarget:self action:@selector(onShowFilter:) forControlEvents:UIControlEventTouchUpInside];
        [btnFilter setTitle:@"不同参数"];
        [self addSubview:btnFilter];
        [btnFilter release];
        
        [btnAll setSelected:TRUE];
        isShowAll = TRUE;
    
        carSpecArray = [[NSMutableArray arrayWithCapacity:3]retain];
        currentDatas = [self fullfillArray];
        
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(onExpendSection:) name:@"Notification_Section_Expend" object:nil];
    }
    return self;
}

-(NSMutableArray*)fullfillArray
{
    
    NSArray * carBasicParas = [[ResourceLoader getInstance]getCarBasicParas];
    
    NSMutableArray* array = [NSMutableArray new];
    
    ComparisonGroup * group = nil;
    ComparisonItem * item = nil;
    
    for(NSDictionary * dic in carBasicParas)
    {
        NSString * groupTitle = [dic objectForKey:@"mainname"];
        
        if(group==nil||![group.groupTitle isEqualToString:groupTitle])
        {
            group = [ComparisonGroup new];
            group.groupTitle = groupTitle;
            group.isExpend = TRUE;
            group.itemArray = [NSMutableArray array];
            group.itemFiterArray = [NSMutableArray array];
            [array addObject:group];
            [group release];
        }
        
        item = [ComparisonItem new];
        item.paraId = [[dic objectForKey:@"paraid"]intValue];
        item.paraValue = [dic objectForKey:@"subname"];
        item.carValueArray = [NSMutableArray array];
        [group.itemArray addObject:item];
        [item release];
    }
    return array;
}

-(void)onExpendSection:(NSNotification*)notify
{
    NSDictionary * userInfo = [notify userInfo];
    BOOL isExpend = [[userInfo objectForKey:@"isexpend"]boolValue];
    NSInteger section = [[userInfo objectForKey:@"section"]intValue];

    ComparisonGroup * group = [currentDatas objectAtIndex:section];
    group.isExpend = isExpend;
    NSArray * array = isShowAll?group.itemArray:group.itemFiterArray;
    
    if(!isExpend)
    {
        
        NSMutableArray *deleteIndexPaths = [NSMutableArray arrayWithCapacity:[array count]];
        for(NSInteger i=[array count]-1;i>=0;i--)
        {
            [deleteIndexPaths addObject: [NSIndexPath indexPathForRow:i inSection:section]];
        }

        [tableView beginUpdates];
        [tableView deleteRowsAtIndexPaths:deleteIndexPaths withRowAnimation:UITableViewRowAnimationFade];
        [tableView endUpdates];
    }
    else
    {
    
        NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithCapacity:[array count]];
        for(NSInteger i=0;i<[array count];i++)
        {
            [insertIndexPaths addObject:[NSIndexPath indexPathForRow:i inSection:section]];
        }
        [tableView beginUpdates];
        [tableView insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];
        [tableView endUpdates];
    }
}

//添加车
-(void)onAddCar:(id)sender
{
    ComparisonSelectView * autoSelectView = [ComparisonSelectView instance];
    [autoSelectView showWithDidSelectBlock:^{
            if(autoSelectView.selectAutoId>0)
            {
                DFLog(@"======%d", autoSelectView.selectAutoId);
                NSInteger carSpecId = autoSelectView.selectAutoId;
                [self addCompareCar:carSpecId];
            }
        }  cancelSelectBlock:^{DLog(@"no auto selected");}];
}

//移除车
-(void)onRemoveCar:(id)sender
{
    ComparisonCarHeader * header = (ComparisonCarHeader*)(((UIButton*)sender).superview);

    NSInteger carIndex = header.carIndex;
    [self removeCompareCar:carIndex];
}

//显示所有参数
-(void)onShowAll:(id)sender
{
    if(btnAll.selected) return;
    btnAll.selected = TRUE;
    btnFilter.selected = FALSE;
    [self filterCompareCar:TRUE];
}

//显示不同参数
-(void)onShowFilter:(id)sender
{
    if(btnFilter.selected)return;
    btnFilter.selected = TRUE;
    btnAll.selected = FALSE;

    [self filterCompareCar:FALSE];
}

-(void)filterCompareCar:(BOOL)flag;
{
    
    if(!flag) //进行筛选
    {
        for(ComparisonGroup * group in currentDatas)
        {
            [group.itemFiterArray removeAllObjects];

            for(ComparisonItem * item in group.itemArray)
            {
                NSInteger paraCount = [item.carValueArray count];
                NSInteger i = 0;
                if(paraCount>1)
                {
                    i=1;
                    NSString * para = [item.carValueArray objectAtIndex:0];
                    for(;i<paraCount;i++)
                    {
                        if(![[item.carValueArray objectAtIndex:i] isEqual:para])
                        {
                            break;
                        }
                    }
                }
                
                if(i<paraCount) //参数不一致
                {
                    [group.itemFiterArray addObject:item];
                }
            }
        }
    }

    isShowAll = flag;
    [tableView reloadData];
}

-(void)addCompareCar:(NSInteger)carSpecId
{
    for(NSDictionary * dic in carSpecArray)
    {
        if([[dic objectForKey:@"specid"]intValue]==carSpecId)
            return;
    }
    
    NSArray * items = [[ResourceLoader getInstance]getCarBasicParasByCarSpecId:carSpecId];
    NSInteger index = 0;
    for(ComparisonGroup * group in currentDatas)
    {
        for(ComparisonItem * item in group.itemArray)
        {
            NSDictionary * dic = [items objectAtIndex:index];
            [item.carValueArray addObject:[dic objectForKey:@"paravalue"]];
            index ++;
        }
    }

    NSString * carName = [[items objectAtIndex:0]objectForKey:@"paravalue"];
    
    NSDictionary * carInfo = [NSDictionary dictionaryWithObjectsAndKeys:
                              [NSNumber numberWithInt:carSpecId],@"specid",
                              carName,@"name",[NSNumber numberWithInt:carNumber],@"index",
                              nil];
    
    [carSpecArray addObject:carInfo];
    carNumber++;
    [self reLayout];
}

-(void)removeCompareCar:(NSInteger)carIndex
{
    if(carIndex<0||carIndex>=[carSpecArray count])
        return;
    
    [carSpecArray removeObjectAtIndex:carIndex];
    
    for(ComparisonGroup * group in currentDatas)
    {
        for(ComparisonItem * item in group.itemArray)
        {
            [item.carValueArray removeObjectAtIndex:carIndex];
        }
    }
    carNumber--;
    [self reLayout];
}


//界面更新
-(void)reLayout
{
    if(currentDatas==nil)
        return;
    if(carNumber<0||carNumber>3)
        return;

    //添加按钮
    [addBtn setFrame:CGRectMake((carNumber)*(BARWIDTH+10)+FirstWIDTH,
                                addBtn.frame.origin.y,
                                addBtn.frame.size.width,
                                addBtn.frame.size.height)];
    //车型上部的header
    
    for(UIView * v in self.subviews)
    {
        if([v isKindOfClass:[ComparisonCarHeader class]])
        {
            [v removeFromSuperview];
        }
    }
    ComparisonCarHeader * header = nil;
    NSInteger index = 0;
    //CGFloat left = BARWIDTH+10;
    CGFloat left = FirstWIDTH;
    
    for(NSDictionary * dic in carSpecArray)
    {
        header = [[ComparisonCarHeader alloc]initWithFrame:CGRectMake(left,0, BARWIDTH, 50)];
        header.carSpecId = [[dic objectForKey:@"specid"]intValue];
        header.carIndex = index++;
        [header setTitle:[dic objectForKey:@"name"]];
        [self addSubview:header];
        [header release];
        left += BARWIDTH+10;
        [header->removeBtn addTarget:self action:@selector(onRemoveCar:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    //参数比对的table
    [tableView setFrame:CGRectMake(tableView.frame.origin.x,
                                   tableView.frame.origin.y,
                                   addBtn.frame.origin.x,
                                   tableView.frame.size.height)];
    [tableView reloadData];
}



#pragma mark - TableView Delegate & DataSource


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    ComparisonGroup * group = [currentDatas objectAtIndex:section];
    return group.isExpend?(isShowAll?[group.itemArray count]:[group.itemFiterArray count]):0;
}

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    return currentDatas == nil?0:[currentDatas count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 30;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    ComparisonTableHeader * header = [[ComparisonTableHeader alloc]initWithFrame:CGRectMake(0, 0, BARWIDTH, 40)];
    header.sectionIndex = section;
    [header loadData:[currentDatas objectAtIndex:section]];
    return [header autorelease];
}

- (UITableViewCell*)tableView:(UITableView *)tView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ComparisonTableCell* cell = [tView dequeueReusableCellWithIdentifier:@"ComparisonTableCell"];
    if(cell == nil)
    {
        cell = [[[ComparisonTableCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:@"ComparisonTableCell"] autorelease];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }
    
    ComparisonGroup * group = [currentDatas objectAtIndex:indexPath.section];
    
    ComparisonItem * cellData = nil;
    if(isShowAll)
    {
        cellData = [group.itemArray objectAtIndex:indexPath.row];
    }
    else
    {
        cellData = [group.itemFiterArray objectAtIndex:indexPath.row];
    }
    [cell loadData:cellData Row:indexPath.row];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}


-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    SafeRelease(carSpecArray);
    SafeRelease(currentDatas);
    [super dealloc];
}

@end
